import { getUserCollections, addCollection, cancelCollection, checkUserCollected, getActivityCollectionCount } from '@/api/collection'

const state = {
  collections: [],
  total: 0,
  loading: false,
  isCollected: false,
  collectionCount: 0
}

const mutations = {
  SET_COLLECTIONS: (state, collections) => {
    state.collections = collections
  },
  SET_TOTAL: (state, total) => {
    state.total = total
  },
  SET_LOADING: (state, loading) => {
    state.loading = loading
  },
  SET_IS_COLLECTED: (state, isCollected) => {
    state.isCollected = isCollected
  },
  SET_COLLECTION_COUNT: (state, count) => {
    state.collectionCount = count
  }
}

const actions = {
  // 获取用户收藏列表
  getUserCollections({ commit }, params) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      getUserCollections(params).then(response => {
        const { data } = response
        commit('SET_COLLECTIONS', data.records || [])
        commit('SET_TOTAL', data.total || 0)
        commit('SET_LOADING', false)
        resolve(data)
      }).catch(error => {
        commit('SET_LOADING', false)
        reject(error)
      })
    })
  },
  
  // 添加收藏
  addCollection({ commit }, activityId) {
    return new Promise((resolve, reject) => {
      addCollection(activityId).then(response => {
        commit('SET_IS_COLLECTED', true)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  
  // 取消收藏
  cancelCollection({ commit }, activityId) {
    return new Promise((resolve, reject) => {
      cancelCollection(activityId).then(response => {
        commit('SET_IS_COLLECTED', false)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  
  // 检查用户是否已收藏活动
  checkUserCollected({ commit }, activityId) {
    return new Promise((resolve, reject) => {
      checkUserCollected(activityId).then(response => {
        const { data } = response
        commit('SET_IS_COLLECTED', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  
  // 获取活动收藏数量
  getActivityCollectionCount({ commit }, activityId) {
    return new Promise((resolve, reject) => {
      getActivityCollectionCount(activityId).then(response => {
        const { data } = response
        commit('SET_COLLECTION_COUNT', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 